package com.fc.campusapplicationsystem.service;

import com.fc.campusapplicationsystem.mapper.ReListMapper;
import com.fc.campusapplicationsystem.model.Consumer;
import com.fc.campusapplicationsystem.model.ReList;
import com.fc.campusapplicationsystem.model.Serviceman;
import com.fc.campusapplicationsystem.model.Superuser;
import com.fc.campusapplicationsystem.util.FileTools;
import com.fc.campusapplicationsystem.util.TimeUtil;
import com.fc.campusapplicationsystem.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:16
 */
@Service
public class ReListServiceImpl implements ReListService {

    private final static String UPLOAD_ADDRESS = "/uploadImg/";
    private final static String LOCAL_ADDRESS = "d:/uploadImg/";

    @Value("${exchange.account}")
    private String account;

    @Value("${exchange.password}")
    private String password;

    @Value("${exchange.emailAddress}")
    private String emailAddress;

    @Autowired
    private ReListMapper reListMapper;

    @Autowired
    ServicemanService servicemanService;

    @Autowired
    SuperuserService superuserService;

    @Autowired
    MailService mailService;


    @Override
    public Integer add(ReList reList) {
        Integer result = reListMapper.insertSelective(reList);
        if (result == 1) {
            // 向管理人员发送新增工单信息
            List<Superuser> list = superuserService.listAll();
            List<String> recipientTo = new ArrayList<>();
            for (Superuser superuser : list) {
                //加入后台所有管理人员邮箱
                recipientTo.add(superuser.getSuperuserEmail());
            }
//            mailService.sendMail(account, password,
//                    "chery", emailAddress, "新增工单待分配", recipientTo, "您有新的工单待分配处理!");
        }
//        MonitorUtil.informToOn(reList);
        return result;
    }

    @Override
    public String upload(MultipartFile file) {
        String realpath = null;
        if (!file.isEmpty()) {
            String path = WebUtil.getRequest().getServletContext().getRealPath("/static/uploads");
            System.out.println("上传路径:" + path);
            System.out.println("上传的文件类型:" + file.getContentType());
            //上传的文件名
            String fileName = file.getOriginalFilename();
            File filePath = new File(path, fileName);
            //判断路径是否存在，如果不存在则创建一个
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            try {
                realpath = path + File.separator + fileName;
                file.transferTo(new File(realpath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return realpath;
    }


    /**
     * 文件上传,上传到本地磁盘
     *
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return null;
        }
        String fileName = file.getOriginalFilename();
        fileName = FileTools.renameToUUID(fileName);
        try {
            FileTools.uploadFiles(file.getBytes(), LOCAL_ADDRESS, fileName);
        } catch (Exception e) {
        }
        return UPLOAD_ADDRESS + fileName;
    }

    @Override
    public List<ReList> list(String key) {
        List<ReList> reLists = new ArrayList<>();
        Example example = new Example(ReList.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isEmpty(key)) {
            reLists = reListMapper.selectAll();
        } else {
            criteria.andLike("userId", "%" + key + "%");
            reLists = reListMapper.selectByExample(example);
        }
        return reLists;
    }

    @Override
    public Integer update(Integer id) {
        ReList reList = reListMapper.getId(id);
        String datePoor = TimeUtil.getDatePoor(new Date(), reList.getAssignTime());
        reList.setId(id)
                .setState(2)
                .setResolveTime(datePoor)
                .setEndTime(new Date());
        return reListMapper.updateByPrimaryKey(reList);
    }

    @Override
    public Integer delete(Integer id) {
        return reListMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer assign(ReList reList) {
        ReList r = reListMapper.getId(reList.getId());
        String datePoor = TimeUtil.getDatePoor(new Date(), r.getStartTime());
        reList.setState(1)
                .setAssignTime(new Date())
                .setResponseTime(datePoor);
        Integer result = reListMapper.assign(reList);
        // 发送邮件
        if (result == 1) {
            // 向指派维修人员发送邮件
            Serviceman serviceman = servicemanService.get(reList.getServiceId());
            List<String> recipientTo = new ArrayList<>();
            recipientTo.add(serviceman.getServiceEmail());
            mailService.sendMail(account, password,
                    "chery", emailAddress, "派单", recipientTo, "您有新的工单,请查看处理!");
        }
        return result;
    }

    @Override
    public List<ReList> myRepair() {
        Consumer consumer = (Consumer) WebUtil.getSession().getAttribute("consumer");
        return reListMapper.myRepair(consumer.getId());
    }

    @Override
    public List<ReList> myAssign() {
        Serviceman serviceman = (Serviceman) WebUtil.getSession().getAttribute("serviceman");
        return reListMapper.myAssign(serviceman.getId());
    }

    @Override
    public ReList getById(Integer id) {
        return reListMapper.getId(id);
    }

    @Override
    public Integer updateRelist(ReList reList) {
        return reListMapper.updateByPrimaryKey(reList);
    }
}
